<?php


    // Author: Tomasz Durka
    // Date: 4th April 2007
    // Prints out a HTML submit tag
    
    
  function submit_to ($value, array $params = array()) {
    static $iterator = 0;
    $iterator++;
    $options = array();
    
    
    
    
    $id = "submit_to_tag_{$iterator}";
    $style = '';
    $name = '';
    $generic = '';
    $confirm = '';
    $autoloader = false;
    $loader = false;
    $before = '';
    $on_click = '';
    $disabled = '';
    $url = '';
    $update = false;
    $serialize = false;
    $success = '';
    $complete = '';
    $class = ' class="submit"';
    
    foreach ($params as $_name => $_value) {
      switch ($_name) {
        case 'id':
          $id = "{$_value}";
        break;
        case 'class':
          $class = " {$_name}=\"{$_value}\" submit";
        break;
        case 'style':
        case 'name':
          $generic .= " {$_name}=\"{$_value}\"";
        break;
        case 'confirm':
          $confirm = "if (!confirm('{$_value}')) return false;";
        break;
        case 'autoloader':
        case 'loader':
        case 'before':
        case 'on_click':
        case 'url':
        case 'update':
        case 'success':
          $$_name = $_value;
        break;
        case 'complete':
          $options[] = "onComplete: function () {{$_value}}";
        break;
        case 'insertion':
          $options[] = "insertion: Insertion." . ucwords($_value);
        break;
        case 'serialize':
          $options[] = "parameters:Form.serialize($({$_value}))";
        break;
        case 'disabled':
          if ($_value == true) {
            $disabled = " disabled=\"disabled\"";
          }
        break;
      }
    }
    $before_default = "$('{$id}').disabled = true;";
    $success_default = "$('{$id}').disabled = false;";
    if ($autoloader) {
      $before_default .= "$(this).up().descendants().invoke('hide');$(this).up().getElementsBySelector('.loader').each(function(e){e.show();e.descendants().invoke('show');});";
      $success_default .= "parentNode.descendants().invoke('toggle');";
    } elseif ($loader) {
      $before_default .= "{$loader}.show();";
      $success_default .= str_replace ("$(this)", "$('{$id}')", $loader) . ".hide();";
    }
    
    $options[] = "evalScripts:true";
    $options[] = "asynchronous:true";
    $options[] = "onSuccess: function () {{$success_default}{$success}}";
    $options = implode (', ', $options);
    
    if ($update) {
      $request = "new Ajax.Updater($({$update}), '/{$url}', {{$options}});";
    } else {
      $request = "new Ajax.Request('/{$url}', {{$options}});";
    }
    $returned = "<input type=\"submit\" id=\"{$id}\" value=\"{$value}\"{$class}{$generic}{$disabled} onClick=\"{$confirm}{$before_default}{$on_click}{$before}{$request} return false;\" />";
    return $returned;
  }

?>